package com.UnionPayCenter.service.serviceImpl;


import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.distribution.dto.DistributionBaseDTO;
import com.UnionPayCenter.distribution.service.DistributionOperatorService;
import com.UnionPayCenter.entity.*;
import com.UnionPayCenter.entity.vo.ShopInfoVo;
import com.UnionPayCenter.entity.vo.ShopLinkVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.*;
import com.UnionPayCenter.account.service.AccountTypeService;
import com.UnionPayCenter.operation.entity.ActivityConfig;
import com.UnionPayCenter.operation.enums.ActivityOperationTypeEnum;
import com.UnionPayCenter.operation.manager.ActivityConfigManager;
import com.UnionPayCenter.service.IShopService;
import com.UnionPayCenter.service.IWechatService;
import com.UnionPayCenter.shop.ShopManager;
import com.UnionPayCenter.shop.domain.ShopMerchant;
import com.UnionPayCenter.shop.request.ShopUpdateRequest;
import com.UnionPayCenter.util.FileUtil;
import com.UnionPayCenter.util.StringUtils;
import com.UnionPayCenter.util.ZipUtil;
import com.UnionPayCenter.wechat.WXCardSignatureUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Param:
 * @return:
 * @Author: bite
 * @Date: 2019/4/25
 */
@Service
@Transactional
public class ShopServiceImpl implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private ConfMapper confMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private IntegralRuleMapper ruleMapper;

    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @Autowired
    private ShopCardInfoMapper shopCardInfoMapper;

    @Autowired
    private UserLevelMapper userLevelMapper;

    @Autowired
    private AccountTypeService accountTypeService;

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private DistributionOperatorService distributionOperatorService;

    @Autowired
    private ActivityConfigManager activityConfigManager;

    @Autowired
    private ShopManager shopManager;

    @Override
    public Integer create(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer type = jsonParam.getInteger("type");
        String name = jsonParam.getString("shopName");
        String tel = jsonParam.getString("shopTel");
        String address = jsonParam.getString("shopAddress");
        String detailAddress = jsonParam.getString("shopDetailAddress");

        ShopEntity shop = new ShopEntity();
        shop.setType(type);
        shop.setShopName(name);
        shop.setShopTel(tel);
        shop.setShopAddress(address);
        shop.setShopDetailAddress(detailAddress);

        int count = shopMapper.insertSelective(shop);
        if (count != 0) {
            //添加管理员与商铺关联
            RelationEntity relationEntity = new RelationEntity();
            relationEntity.setManagerId(managerId);
            relationEntity.setShopId(shop.getShopId());
            relationMapper.insertSelective(relationEntity);

            //添加线上注册渠道
            ChannelEntity channelEntity = new ChannelEntity();
            channelEntity.setShopId(shop.getShopId());
            channelEntity.setType(type);
            channelEntity.setName("线上注册");
            channelEntity.setShortName("online");
            channelMapper.insertSelective(channelEntity);

            //添加手动录入渠道
            ChannelEntity channelEntity1 = new ChannelEntity();
            channelEntity1.setShopId(shop.getShopId());
            channelEntity1.setType(2);
            channelEntity1.setName("手动录入");
            channelEntity1.setShortName("artificial");
            channelMapper.insertSelective(channelEntity1);

            //添加注册积分赠送规则
            IntegralRuleEntity ruleEntity = new IntegralRuleEntity();
            ruleEntity.setType(0);
            ruleEntity.setIsGive(0);
            ruleEntity.setNumber(50);
            ruleEntity.setShopId(shop.getShopId());
            ruleMapper.insertSelective(ruleEntity);

            //添加商铺配置信息
            ShopInfoEntity shopInfoEntity = new ShopInfoEntity();
            shopInfoEntity.setShopId(shop.getShopId());
            shopInfoMapper.insertSelective(shopInfoEntity);

            //添加会员等级
            this.addUserLevel(shop.getShopId());

            //添加账户类型
            this.addAccountType(shop.getShopId());

            //商户分销初始化
            DistributionBaseDTO baseDTO = new DistributionBaseDTO();
            baseDTO.setBId(Long.valueOf(shop.getShopId()));
            baseDTO.setShopId(Long.valueOf(shop.getShopId()));
            distributionOperatorService.distributionInitTemplate(baseDTO);

            ActivityConfig activityConfig = new ActivityConfig();
            activityConfig.setActivityOperationType(ActivityOperationTypeEnum.BALANCE_PAY);
            activityConfig.setCoupon(1);
            activityConfig.setMemberCardDiscount(1);
            activityConfig.setShopId(shop.getShopId());
            activityConfigManager.addActivityConfig(activityConfig);

            return shop.getShopId();
        } else {
            throw new ApiException(ErrorCodeEnum.SW12.code(), String.format(ErrorCodeEnum.SW12.msg(), "创建商铺"));
        }
    }

    private void addAccountType(Integer shopId) {
        accountTypeService.createAccountType(shopId);

    }

    private void addUserLevel(Integer shopId) {
        List<UserLevelEntity> list = new ArrayList<>();
        UserLevelEntity userLevelEntity = new UserLevelEntity();
        userLevelEntity.setName("普通会员");
        userLevelEntity.setLevelCondition(0);
        userLevelEntity.setDiscount(10.0D);
        userLevelEntity.setSort(1);
        userLevelEntity.setShopId(shopId);
        list.add(userLevelEntity);

        UserLevelEntity userLevelEntity2 = new UserLevelEntity();
        userLevelEntity2.setName("青铜会员");
        userLevelEntity2.setLevelCondition(100);
        userLevelEntity2.setDiscount(10.0D);
        userLevelEntity2.setSort(2);
        userLevelEntity2.setShopId(shopId);
        list.add(userLevelEntity2);

        UserLevelEntity userLevelEntity3 = new UserLevelEntity();
        userLevelEntity3.setName("白银会员");
        userLevelEntity3.setLevelCondition(500);
        userLevelEntity3.setDiscount(10.0D);
        userLevelEntity3.setSort(3);
        userLevelEntity3.setShopId(shopId);
        list.add(userLevelEntity3);

        UserLevelEntity userLevelEntity4 = new UserLevelEntity();
        userLevelEntity4.setName("黄金会员");
        userLevelEntity4.setLevelCondition(1500);
        userLevelEntity4.setDiscount(10.0D);
        userLevelEntity4.setSort(4);
        userLevelEntity4.setShopId(shopId);
        list.add(userLevelEntity4);

        UserLevelEntity userLevelEntity5 = new UserLevelEntity();
        userLevelEntity5.setName("铂金会员");
        userLevelEntity5.setLevelCondition(5000);
        userLevelEntity5.setDiscount(10.0D);
        userLevelEntity5.setSort(5);
        userLevelEntity5.setShopId(shopId);
        list.add(userLevelEntity5);

        UserLevelEntity userLevelEntity6 = new UserLevelEntity();
        userLevelEntity6.setName("钻石会员");
        userLevelEntity6.setLevelCondition(8000);
        userLevelEntity6.setDiscount(10.0D);
        userLevelEntity6.setSort(6);
        userLevelEntity6.setShopId(shopId);
        list.add(userLevelEntity6);

        userLevelMapper.insertBatch(list);
    }

    @Override
    public ShopEntity findShop(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            ShopEntity shop = shopMapper.selectByPrimaryKey(shopId);
            return shop;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean update(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String name = jsonParam.getString("shopName");
            String tel = jsonParam.getString("shopTel");
            String address = jsonParam.getString("shopAddress");
            String detailAddress = jsonParam.getString("shopDetailAddress");

            ShopEntity shop = new ShopEntity();
            shop.setShopId(shopId);
            shop.setShopName(name);
            shop.setShopTel(tel);
            shop.setShopAddress(address);
            shop.setShopDetailAddress(detailAddress);

            shopMapper.updateByPrimaryKeySelective(shop);
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopLinkVo findLink(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            ConfEntity memberCenterLink = confMapper.selectByKey(ConstantInterface.LINK_MEMBER_CENTER);
            ConfEntity registryLink = confMapper.selectByKey(ConstantInterface.LINK_REGISTRY);
            ConfEntity shopInfoLink = confMapper.selectByKey(ConstantInterface.LINK_SHOP_INFO);
            ConfEntity integralLink = confMapper.selectByKey(ConstantInterface.LINK_INTEGRAL);

            ShopLinkVo vo = new ShopLinkVo();
            vo.setQrCode(String.format(registryLink.getConfValue(), shopId));
            vo.setMemberCenterLink(String.format(memberCenterLink.getConfValue(), shopId));
            vo.setRegistryLink(String.format(registryLink.getConfValue(), shopId));
            vo.setShopInfoLink(String.format(shopInfoLink.getConfValue(), shopId));
            vo.setIntegralLink(String.format(integralLink.getConfValue(), shopId));
            return vo;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopEntity getShop(JSONObject jsonParam) {
        Integer shopId = jsonParam.getInteger("shopId");
        ShopEntity shop = shopMapper.selectByPrimaryKey(shopId);
        return shop;
    }

    @Override
    public List<ShopEntity> findList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        List<ShopEntity> list = shopMapper.selectList(managerId);
        return list;
    }

    @Override
    public ShopInfoVo findShopInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            ShopInfoVo vo = shopInfoMapper.selectShopInfo(shopId);
            return vo;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean updateShopInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
//            String appName = jsonParam.getString("appName");
            String appId = jsonParam.getString("appId");
            String appSecret = jsonParam.getString("appSecret");
//            String appGhId = jsonParam.getString("appGhId");
            String wechatId = jsonParam.getString("wechatId");
            String wechatSecret = jsonParam.getString("wechatSecret");
            String ylMerchant = jsonParam.getString("ylMerchant");
//            String membercardId = jsonParam.getString("membercardId");
            Integer payChannel = jsonParam.getInteger("payChannel");

//            //判断名称是否已存在
//            List<ShopInfoEntity> list = shopInfoMapper.selectByName(appName);
//            if(list != null && !list.isEmpty()){
//                for (ShopInfoEntity info : list) {
//                    if(info.getShopId() != shopId){
//                        throw new ApiException(ErrorCodeEnum.SE601);
//                    }
//                }
//            }
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
            if (shopInfoEntity != null) {
//                shopInfoEntity.setAppName(appName);
                shopInfoEntity.setShopId(shopId);
                shopInfoEntity.setAppId(appId);
                shopInfoEntity.setAppSecret(appSecret);
//                shopInfoEntity.setAppGhId(appGhId);
                shopInfoEntity.setWechatId(wechatId);
                shopInfoEntity.setWechatSecret(wechatSecret);
                shopInfoEntity.setYlMerchant(ylMerchant);
//                shopInfoEntity.setMembercardId(membercardId);
                shopInfoEntity.setMerchantId(ylMerchant);
                shopInfoEntity.setPayChannel(payChannel);
                shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
            } else {
                shopInfoEntity = new ShopInfoEntity();
//                shopInfoEntity.setAppName(appName);
                shopInfoEntity.setShopId(shopId);
                shopInfoEntity.setAppId(appId);
                shopInfoEntity.setAppSecret(appSecret);
//                shopInfoEntity.setAppGhId(appGhId);
                shopInfoEntity.setWechatId(wechatId);
                shopInfoEntity.setWechatSecret(wechatSecret);
                shopInfoEntity.setYlMerchant(ylMerchant);
//                shopInfoEntity.setMembercardId(membercardId);
                shopInfoEntity.setMerchantId(ylMerchant);
                shopInfoEntity.setPayChannel(payChannel);
                shopInfoMapper.insertSelective(shopInfoEntity);
            }
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean updateShopInfo(ShopUpdateRequest shopUpdateRequest) throws Exception {
        ManagerEntity managerEntity = managerMapper.selectByShopId(shopUpdateRequest.getManagerId(), shopUpdateRequest.getShopId());
        // if (managerEntity != null) {

        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopUpdateRequest.getShopId());
        if (shopInfoEntity != null) {
            ShopMerchant shopMerchant = shopManager.getShopMerchantInfo(shopInfoEntity, shopUpdateRequest.getBizMachId(),
                    shopUpdateRequest.getYlTid());
            if (Objects.isNull(shopMerchant)) {
                throw new ApiException(ErrorCodeEnum.SC2);
            }
            shopInfoEntity.setShopId(shopUpdateRequest.getShopId());
            shopInfoEntity.setAppId(shopUpdateRequest.getAppId());
            shopInfoEntity.setAppSecret(shopUpdateRequest.getAppSecret());
            shopInfoEntity.setWechatId(shopUpdateRequest.getWechatId());
            shopInfoEntity.setWechatSecret(shopUpdateRequest.getWechatSecret());
            shopInfoEntity.setYlMerchant(shopMerchant.getSubMerchant());
            shopInfoEntity.setMerchantId(shopMerchant.getSubMerchant());

            shopInfoEntity.setYlParentMerchant(shopMerchant.getParentMerchant());
            shopInfoEntity.setYlTid(shopMerchant.getTerminalId());
            shopInfoEntity.setYlPaymentTag(shopMerchant.getPaymentTag());
            shopInfoEntity.setBizMachId(shopMerchant.getBizMchId());
            shopInfoEntity.setPayChannel(shopUpdateRequest.getPayChannel());

            //判断小程序appid，appsecret是否合法
            if (!StringUtils.isNullStr(shopUpdateRequest.getAppId()) && !StringUtils.isNullStr(shopUpdateRequest.getAppSecret())) {
                WXCardSignatureUtil.getAccessToken(shopUpdateRequest.getAppId(), shopUpdateRequest.getAppSecret());
            }
            shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
        } else {
            shopInfoEntity = new ShopInfoEntity();
            shopInfoEntity.setShopId(shopUpdateRequest.getShopId());
            shopInfoEntity.setAppId(shopUpdateRequest.getAppId());
            shopInfoEntity.setAppSecret(shopUpdateRequest.getAppSecret());
            shopInfoEntity.setWechatId(shopUpdateRequest.getWechatId());
            shopInfoEntity.setWechatSecret(shopUpdateRequest.getWechatSecret());
            shopInfoEntity.setPayChannel(shopUpdateRequest.getPayChannel());
            shopInfoEntity.setYlTid(shopUpdateRequest.getYlTid());
            shopInfoEntity.setBizMachId(shopUpdateRequest.getBizMachId());

            //判断小程序appid，appsecret是否合法
            if (!StringUtils.isNullStr(shopUpdateRequest.getAppId()) && !StringUtils.isNullStr(shopUpdateRequest.getAppSecret())) {
                WXCardSignatureUtil.getAccessToken(shopUpdateRequest.getAppId(), shopUpdateRequest.getAppSecret());
            }
            shopInfoMapper.insertSelective(shopInfoEntity);
        }
        return true;
//        } else {
//            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
//        }
    }

    @Override
    public void updateShopInfo(ShopInfoEntity shopInfoEntity) {
        Integer shopId = shopInfoEntity.getShopId();
        if (shopId == null) {
            shopInfoMapper.insertSelective(shopInfoEntity);
        } else {
            ShopInfoEntity dbShopInfo = shopInfoMapper.selectByShop(shopId);
            if (dbShopInfo != null) {
                shopInfoMapper.updateByPrimaryKeySelective(shopInfoEntity);
            } else {
                shopInfoMapper.insertSelective(shopInfoEntity);
            }
        }
    }

    @Override
    public ShopInfoEntity wechatPayGetShopInfo(Integer shopId) {
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        if (shopInfoEntity == null) {
            throw new ApiException(ErrorCodeEnum.WP8001.code(), ErrorCodeEnum.WP8001.msg());
        }
//        if(StringUtils.isNullStr(shopInfoEntity.getWechatId()) || StringUtils.isNullStr(shopInfoEntity.getWechatSecret())){
//            throw new ApiException(ErrorCodeEnum.WP8002.code(), ErrorCodeEnum.WP8002.msg());
//        }
        if (StringUtils.isNullStr(shopInfoEntity.getAppId()) || StringUtils.isNullStr(shopInfoEntity.getAppSecret())) {
            throw new ApiException(ErrorCodeEnum.WP8003);
        }
//        if(StringUtils.isNullStr(shopInfoEntity.getMerchantId()) || StringUtils.isNullStr(shopInfoEntity.getMerchantSecret())){
//            throw new ApiException(ErrorCodeEnum.WP8004);
//        }
        if (StringUtils.isNullStr(shopInfoEntity.getYlMerchant())) {
            throw new ApiException(ErrorCodeEnum.WP8008);
        }
        return shopInfoEntity;
    }

    @Override
    public ShopInfoEntity wechatGetShopInfo(Integer shopId) {
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        if (shopInfoEntity == null) {
            throw new ApiException(ErrorCodeEnum.WP8001.code(), ErrorCodeEnum.WP8001.msg());
        }
        if (StringUtils.isNullStr(shopInfoEntity.getWechatId()) || StringUtils.isNullStr(shopInfoEntity.getWechatSecret())) {
            throw new ApiException(ErrorCodeEnum.WP8002.code(), ErrorCodeEnum.WP8002.msg());
        }
        return shopInfoEntity;
    }

    @Override
    public String download(JSONObject jsonParam) throws Exception {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            //获取商铺配置信息
            ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
            if (StringUtils.isNullStr(shopInfoEntity.getAppId())) {
                throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "小程序 appid"));
            }
            if (StringUtils.isNullStr(shopInfoEntity.getAppSecret())) {
                throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "小程序 appsecret"));
            }
            if (StringUtils.isNullStr(shopInfoEntity.getMembercardId())) {
                throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "会员卡id"));
            }
            if (StringUtils.isNullStr(shopInfoEntity.getAppName())) {
                throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "小程序名称"));
            }

            String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "appletCode/bank";
            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/appletCode/" + shopId;
            String newPath = path + "/bank";
            String shopInfoPath = path + "/bank/shopinfo.js";
            String zipPath = "/appletCode/" + shopId + "/bank.zip";

            //删除已有文件夹及压缩包
            FileUtil.deleteDir(path);
            //复制基础文件夹
            FileUtil.copyDir(sourcePath, newPath);
            //根据商铺信息生成配置文件
            FileUtil.writeFile(this.getShopInfoJsContent(shopInfoEntity), shopInfoPath);
            //文件夹打包
            ZipUtil.toZip(newPath, true);

            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.DOMAIN_URL);
            return confEntity.getConfValue() + zipPath;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopInfoEntity getByCardId(String cardId) {
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByCardId(cardId);
        if (shopInfoEntity == null) {
            throw new ApiException(ErrorCodeEnum.WP8001.code(), ErrorCodeEnum.WP8001.msg());
        }
        if (StringUtils.isNullStr(shopInfoEntity.getWechatId()) || StringUtils.isNullStr(shopInfoEntity.getWechatSecret())) {
            throw new ApiException(ErrorCodeEnum.WP8002.code(), ErrorCodeEnum.WP8002.msg());
        }
        return shopInfoEntity;
    }

    @Override
    public Integer getPayChannel(JSONObject jsonParam) {
        Integer shopId = jsonParam.getInteger("shopId");
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        if (shopInfoEntity != null) {
            return shopInfoEntity.getPayChannel();
        }
        return 0;
    }

    @Override
    public ShopCardInfoEntity wechatGetShopCardInfo(Integer shopId) {
        ShopCardInfoEntity cardInfoEntity = shopCardInfoMapper.selectByShop(shopId);
        return cardInfoEntity;
    }

    @Override
    public boolean updateShopCardId(int shopId, String cardId) {
        int count = shopInfoMapper.updateShopCardId(shopId, cardId);
        return count == 0 ? false : true;
    }

    @Override
    public JSONObject getCardActivate(JSONObject jsonParam) {
        Integer shopId = jsonParam.getInteger("shopId");
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByShop(shopId);
        if (shopInfoEntity != null && !StringUtils.isNullStr(shopInfoEntity.getWechatEncryptCardId()) && !StringUtils.isNullStr(shopInfoEntity.getWechatBiz())) {
            JSONObject json = new JSONObject();
            json.put("encrypt_card_id", shopInfoEntity.getWechatEncryptCardId());
            json.put("outer_str", shopId);
            json.put("biz", shopInfoEntity.getWechatBiz());
            return json;
        }
        JSONObject json = wechatService.activateCard(shopId);
        return json;
    }

    @Override
    public ShopCardInfoEntity getCardInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer infoId = jsonParam.getInteger("infoId");
            ShopCardInfoEntity card = shopCardInfoMapper.selectByPrimaryKey(infoId);
            return card;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }

    }

    @Override
    public PageInfo<ShopCardInfoEntity> getCardList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            PageHelper.startPage(1, 10);

            List<ShopCardInfoEntity> list = shopCardInfoMapper.selectCardList(shopId);
            PageInfo<ShopCardInfoEntity> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopCardInfoEntity createCard(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            //判断是否存在会员卡
            List<ShopCardInfoEntity> list = shopCardInfoMapper.selectCardList(shopId);
            if (list != null && list.size() > 0) {
                throw new ApiException(ErrorCodeEnum.WC10001);
            }
            //保存会员卡信息
            String backgroundPicUrl = jsonParam.getString("backgroundPicUrl");
            String codeType = jsonParam.getString("codeType");
            String prerogative = jsonParam.getString("prerogative");
            String bonusRules = jsonParam.getString("bonusRules");
            String balanceRules = jsonParam.getString("balanceRules");
            Integer discount = jsonParam.getInteger("discount");
            String logoUrl = jsonParam.getString("logoUrl");
            String brandName = jsonParam.getString("brandName");
            String title = jsonParam.getString("title");
            String color = jsonParam.getString("color");
            String notice = jsonParam.getString("notice");
            String description = jsonParam.getString("description");
            String servicePhone = jsonParam.getString("servicePhone");
            String centerTitle = jsonParam.getString("centerTitle");
            String centerSubTitle = jsonParam.getString("centerSubTitle");
            String timeLimit = jsonParam.getString("timeLimit");
            String requiredForm = jsonParam.getString("requiredForm");
            String optionalForm = jsonParam.getString("optionalForm");

            ShopCardInfoEntity cardInfo = new ShopCardInfoEntity();
            cardInfo.setShopId(shopId);
            cardInfo.setBackgroundPicUrl(backgroundPicUrl);
            cardInfo.setCodeType(codeType);
            cardInfo.setPrerogative(prerogative);
            cardInfo.setBonusRules(bonusRules);
            cardInfo.setBalanceRules(balanceRules);
            cardInfo.setDiscount(discount);
            cardInfo.setLogoUrl(logoUrl);
            cardInfo.setBrandName(brandName);
            cardInfo.setTitle(title);
            cardInfo.setColor(color);
            cardInfo.setNotice(notice);
            cardInfo.setDescription(description);
            cardInfo.setServicePhone(servicePhone);
            cardInfo.setCenterTitle(centerTitle);
            cardInfo.setCenterSubTitle(centerSubTitle);
            cardInfo.setTimeLimit(timeLimit);
            cardInfo.setRequiredForm(requiredForm);
            cardInfo.setOptionalForm(optionalForm);
            shopCardInfoMapper.insertSelective(cardInfo);

            //创建微信会员卡
            String cardId = wechatService.createCard(shopId, cardInfo.getInfoId());
            if (!StringUtils.isNullStr(cardId)) {
                cardInfo.setCardId(cardId);
                //设置开卡信息
                wechatService.setCard(shopId, cardInfo.getInfoId());
                //设置开卡组件
                wechatService.activateCard(shopId);
                return cardInfo;
            }
            throw new ApiException(ErrorCodeEnum.WC10002);
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopCardInfoEntity updateCard(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer infoId = jsonParam.getInteger("infoId");
            ShopCardInfoEntity cardInfo = shopCardInfoMapper.selectByPrimaryKey(infoId);
            //修改会员卡信息
            String backgroundPicUrl = jsonParam.getString("backgroundPicUrl");
            String codeType = jsonParam.getString("codeType");
            String prerogative = jsonParam.getString("prerogative");
            String bonusRules = jsonParam.getString("bonusRules");
            String balanceRules = jsonParam.getString("balanceRules");
            Integer discount = jsonParam.getInteger("discount");
            String logoUrl = jsonParam.getString("logoUrl");
//            String brandName = jsonParam.getString("brandName");
            String title = jsonParam.getString("title");
            String color = jsonParam.getString("color");
            String notice = jsonParam.getString("notice");
            String description = jsonParam.getString("description");
            String servicePhone = jsonParam.getString("servicePhone");
            String centerTitle = jsonParam.getString("centerTitle");
            String centerSubTitle = jsonParam.getString("centerSubTitle");
            String timeLimit = jsonParam.getString("timeLimit");
            String requiredForm = jsonParam.getString("requiredForm");
            String optionalForm = jsonParam.getString("optionalForm");

            cardInfo.setBackgroundPicUrl(backgroundPicUrl);
            cardInfo.setCodeType(codeType);
            cardInfo.setPrerogative(prerogative);
            cardInfo.setBonusRules(bonusRules);
            cardInfo.setBalanceRules(balanceRules);
            cardInfo.setDiscount(discount);
            cardInfo.setLogoUrl(logoUrl);
//            cardInfo.setBrandName(brandName);
            cardInfo.setTitle(title);
            cardInfo.setColor(color);
            cardInfo.setNotice(notice);
            cardInfo.setDescription(description);
            cardInfo.setServicePhone(servicePhone);
            cardInfo.setCenterTitle(centerTitle);
            cardInfo.setCenterSubTitle(centerSubTitle);
            cardInfo.setTimeLimit(timeLimit);
            cardInfo.setRequiredForm(requiredForm);
            cardInfo.setOptionalForm(optionalForm);
            shopCardInfoMapper.updateByPrimaryKeySelective(cardInfo);

            //修改微信会员卡
            boolean isSuccess = wechatService.updateCard(shopId, cardInfo.getInfoId());
            if (isSuccess) {
                //设置开卡信息
                wechatService.setCard(shopId, cardInfo.getInfoId());
                return cardInfo;
            }
            throw new ApiException(ErrorCodeEnum.WC10003);
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public ShopInfoEntity getByAppid(String appid) {
        ShopInfoEntity shopInfoEntity = shopInfoMapper.selectByAppid(appid);
        return shopInfoEntity;
    }

    @Override
    public UserLevelEntity getShopInitialMemberLevel(Integer shopId) {
        return userLevelMapper.selectDefault(shopId);
    }

    public static String getShopInfoJsContent(ShopInfoEntity shopInfoEntity) {
        StringBuffer sb = new StringBuffer();

        sb.append("const shopInfo = {").append("\r\n");
        sb.append("    ").append("\"appid\": \"").append(shopInfoEntity.getAppId()).append("\",\r\n");
        sb.append("    ").append("\"appsecret\": \"").append(shopInfoEntity.getAppSecret()).append("\",\r\n");
        sb.append("    ").append("\"shopId\": ").append(shopInfoEntity.getShopId()).append(",\r\n");
        sb.append("    ").append("\"cardId\": \"").append(shopInfoEntity.getMembercardId()).append("\",\r\n");
        sb.append("    ").append("\"appName\": \"").append(shopInfoEntity.getAppName()).append("\"\r\n");
        sb.append("}").append("\r\n");

        sb.append("\r\n");
        sb.append("module.exports = {").append("\r\n");
        sb.append("    shopInfo : shopInfo").append("\r\n");
        sb.append("}").append("\r\n");
        return sb.toString();
    }
}
